package com.j.lemon.learn.thread.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author lijunjun
 * @Date 2019-04-17 17:34
 * @Description  ReentrantLock和Synchronized都是可重入锁，默认都是非公平锁
 */
public class ReentrantLockDemo {
    public static void main(String[] args) {
        //非公平锁
        ReentrantLock unfairLock = new ReentrantLock();
        //公平锁
        ReentrantLock fairLock = new ReentrantLock(true);

        //可重入演示
        Phone phone = new Phone();
        new Thread(()->{
            phone.sendSMS();
        },"t1").start();

        new Thread(()->{
            phone.sendSMS();
        },"t2").start();

        Thread t3 = new Thread(phone,"t3");
        Thread t4 = new Thread(phone,"t4");
        t3.start();
        t4.start();
    }
}


class Phone implements Runnable {
    public synchronized void sendSMS(){
        System.out.println(Thread.currentThread().getId() + "\t invoked sendSMS()");
        sendEmail();
    }

    public synchronized void sendEmail(){
        System.out.println(Thread.currentThread().getId() + "\t invoked sendEmail()");
    }

    @Override
    public void run() {
        get();
    }
    ReentrantLock reentrantLock = new ReentrantLock();
    private void get() {
        reentrantLock.lock();
        try{
            System.out.println(Thread.currentThread().getId() + "\t invoked get()");
            get1();
        }finally {
            reentrantLock.unlock();
        }
    }

    private void get1() {
        reentrantLock.lock();
        try{
            System.out.println(Thread.currentThread().getId() + "\t invoked get1()");
        }finally {
            reentrantLock.unlock();
        }
    }
}
